#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "myfile.h"
#include "general.h"

void insert_book() {//录入图书
	BOOK book, tmp_book;
	BOOK *point_to_book, *point_to_tmp_book;
	point_to_book = &book;
	point_to_tmp_book = &tmp_book;
	int flag;
	int i;

	int lines;
	lines = lines_of_file("book");


	FILE *fp;
	if ((fp = fopen("book", "ab+")) == NULL) {
		printf("open file failed in function insert_book\n");
		exit(1);
	}

	do {
		flag = 1;
		printf("请输入图书名(最多十个字符)：");
		scanf("%s", point_to_tmp_book->book_name);
		printf("请输入图书编号(最多十个字符)：");
		scanf("%s", point_to_tmp_book->book_id);
		for (i = 0; i < lines; i++) {
			rewind(fp);
			fseek(fp, i * sizeof(BOOK), 0);
			fread(point_to_book, sizeof(BOOK), 1, fp);
			if (strcmp(point_to_tmp_book->book_name, point_to_book->book_name) == 0) {
				if(strcmp(point_to_tmp_book->book_id, point_to_book->book_id) == 0){
					printf("\n该编号已存在请重新输入\n\n");
					break;
				}
			}
		}
		if (i == lines) {
			flag = 0;
		}
	} while(flag);

	 
	printf("请输入图书作者(最多十个字符)：");
	scanf("%s",point_to_tmp_book->book_author);

	printf("请输入图书出版日期（例如2001年5月3日出版则输入20010503）：");
	scanf("%d",&point_to_tmp_book->book_publish_date);

	printf("请输入图书价格：");
	scanf("%f",&point_to_tmp_book->book_price);

	printf("请输入图书出版社(最多十个字符)：");
	scanf("%s",point_to_tmp_book->book_press);
	
	printf("请输入图书类别(最多十个字符)：");
	scanf("%s",point_to_tmp_book->book_category);

	printf("请输入图书入库数：");
	scanf("%d",&point_to_tmp_book->book_original_stock);

	point_to_tmp_book->book_lent = 0;

	point_to_tmp_book->endflag = '\n';

	fseek(fp, 0, 2);
	fwrite(point_to_tmp_book, sizeof(BOOK), 1, fp);
	printf("\n录入成功！回到主菜单\n");
	fclose(fp);
}

void show_book(char *name, int lines) {
	int i;
	FILE *fp;
	BOOK book;
	BOOK *point_to_book;
	point_to_book = &book;

	if ((fp = fopen(name, "rb")) == NULL) {
		printf("open file failed in function show_book");
		exit(1);
	}

	printf("书名\t编号 \t作者\t日期\t价格\t出版社\t类别\t原始库存\t借出\n");
	for (i = 0; i < lines; i++) {
		rewind(fp);
		fseek(fp, i * sizeof(BOOK), 0);
		fread(point_to_book, sizeof(BOOK), 1, fp);
		printf("%s\t%s\t%s\t%d\t%4.2f\t%s\t%s\t%d\t%d\n", point_to_book->book_name, point_to_book->book_id, point_to_book->book_author, point_to_book->book_publish_date, point_to_book->book_price, point_to_book->book_press, point_to_book->book_category, point_to_book->book_original_stock, point_to_book->book_lent);
	}
	printf("\n浏览图书完毕！回到主菜单\n");
	fclose(fp);
}



